package com.skcc.cip.ngms.mail.processor;

import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLStreamReader;

import org.apache.axiom.om.impl.builder.StAXBuilder;
import org.apache.axiom.om.util.StAXUtils;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder;
import org.apache.axis2.AxisFault;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;

import com.microsoft.schemas.exchange.services._2006.messages.SendNotificationDocument;
import com.microsoft.schemas.exchange.services._2006.messages.SendNotificationResponseMessageType;
import com.microsoft.schemas.exchange.services._2006.types.NotificationType;
import com.skcc.cip.ngms.converter.MailTransform;

public class MailNotificationChecker implements Processor{

	public void process(Exchange exchange) throws Exception {
		Object original = exchange.getIn().getBody();
		exchange.setProperty("originRequest", original);
		
		try{
			InputStream stream = exchange.getIn().getBody(InputStream.class);
			
			org.apache.axiom.soap.SOAPEnvelope env = createSOAPEnvelope(stream);
			XMLStreamReader reader = env.getBody().getFirstElement().getXMLStreamReader();
			
			SendNotificationDocument doc = SendNotificationDocument.Factory.parse(reader);
			SendNotificationResponseMessageType messageType = doc.getSendNotification().getResponseMessages().getSendNotificationResponseMessageArray(0);
			
//			String responseClass = messageType.getResponseCode().toString();
//			String responseCode = messageType.getResponseCode().toString();
			
			NotificationType notiType = messageType.getNotification();
			String subscribeId =notiType.getSubscriptionId();
			String previousWatermark;
			String watermark;
			String itemId;
			String itemChangekey;
			String parentFolderId;
			String parentFolderChangekey;
//			if(MailTransform.subscribeList.containsKey(subscribeId)){
				if(notiType.getStatusEventArray().length > 0){
	//				watermark = notiType.getStatusEventArray(0).getWatermark();
	
					exchange.getIn().setHeader("pushcheck", "status");
					exchange.getIn().setBody(subscribeId);
	//				CamelContext camelContext = exchange.getContext();
	//				camelContext.createProducerTemplate().send("direct:sendresult", exchange);
	//				exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
				}
				if(notiType.getNewMailEventArray().length > 0){
					previousWatermark = notiType.getPreviousWatermark();
					watermark = notiType.getNewMailEventArray(0).getWatermark();
					itemId = notiType.getNewMailEventArray(0).getItemId().getId();
					itemChangekey = notiType.getNewMailEventArray(0).getItemId().getChangeKey();
					parentFolderId = notiType.getNewMailEventArray(0).getParentFolderId().getId();
					parentFolderChangekey = notiType.getNewMailEventArray(0).getParentFolderId().getChangeKey();
					
					String msg = "title=" + URLEncoder.encode("신규 메일이 도착하였습니다.&", "UTF-8") +
								"body=" + URLEncoder.encode("메일을 확인하시려면 클릭~&", "UTF-8") +
								"itemId=" + URLEncoder.encode(itemId+"&", "UTF-8") +
								"itemChangekey=" + URLEncoder.encode(itemChangekey+"&", "UTF-8");
//								"parentFolderId=" + URLEncoder.encode(parentFolderId+"&", "UTF-8") +
//								"parentFolderChangekey="+URLEncoder.encode(parentFolderChangekey, "UTF-8");
					exchange.getIn().setHeader("pushcheck", "newmail");
					exchange.setProperty("pushMsg", msg);
					exchange.getIn().setBody(subscribeId);
	//				CamelContext camelContext = exchange.getContext();
	//				camelContext.createProducerTemplate().send("direct:getNewMail", exchange);
	//				exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
				}
				
//			}else{
//				exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
//			}
			
			
//			SendNotificationResponseMessageType sendNotificationResponseType = SendNotificationResponseMessageType.Factory.newInstance();
//			NotificationType notificationType = NotificationType.Factory.newInstance();
//			notificationType.addNewStatusEvent();	
//			
//			sendNotificationResponseType.setNotification(notificationType);
//			
//			OMElement element = (OMElement) env.getFirstElement().getFirstElement().getFirstElement().getFirstOMChild();
//			if(!messageType.equals(element.getLocalName()))
//				throw new Exception("Message type is not SendNotificationResponseMessageType.");
//			String responseClass = element.getAttributeValue(new QName("ResponseClass"));
//			sendNotificationResponseType.setMessageText(responseClass);
//			if(resultClass.equals(responseClass)){
//				String responseCode = ((OMTextImpl) element.getFirstElement().getFirstOMChild()).getText();
//				sendNotificationResponseType.setResponseCode(Enum.forString(responseCode));
//				
//				Iterator<OMChildElementIterator> iter = ((OMElement) element.getFirstElement().getNextOMSibling()).getChildElements();
//				while(iter.hasNext()){
//					OMElement childElement = (OMElement) iter.next();
//					
//					if(subscriptionId.equals(childElement.getLocalName()))
//							sendNotificationResponseType.getNotification().setSubscriptionId(childElement.getText());
//					if(previousWatermark.equals(childElement.getLocalName()))
//						sendNotificationResponseType.getNotification().setPreviousWatermark(childElement.getText());
//					if(moreEvents.equals(childElement.getLocalName()))
//						sendNotificationResponseType.getNotification().setMoreEvents(new Boolean(childElement.getText()));
//					if(statusEvent.equals(childElement.getLocalName()))
//						sendNotificationResponseType.getNotification().getStatusEventArray(0).setWatermark(childElement.getFirstElement().getText());
//				}
//			}
			
			
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	 public SOAPEnvelope createSOAPEnvelope(InputStream in) throws AxisFault {
          try {
              XMLStreamReader xmlreader = StAXUtils.createXMLStreamReader(in);
              StAXBuilder builder = new StAXSOAPModelBuilder(xmlreader, null);
              return (SOAPEnvelope) builder.getDocumentElement();
          } catch (Exception e) {
              throw new AxisFault(e.getMessage(), e);
          }
      }
}
